<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ pageConfige.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button size="small" type="primary" @click="isShowDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">
          <el-table-column label="序号" sortable="" type="index" :index="customIndex" />
          <el-table-column label="图像" sortable="" prop="staffPhoto" width="200">
            <template v-slot="scoped">
              <img
                v-fiximg="require('@/assets/common/meimei.jpg')"
                :src="scoped.row.staffPhoto"
                alt=""
                class="avatar"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="电话" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- v-slot="scoped" -->
            <template v-slot="scoped">
              {{ scoped.row.timeOfEntry|formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <!-- 使用作用域插槽 ,使用emement-ui的状态显示插件 Switch 开关-->
            <template v-slot="scoped">
              <!-- {{ scoped.row.enableState }} -->
              <el-switch
                v-model="scoped.row.enableState"
                :active-value="1"
                :inactive-value="2"
                disabled
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="scoped">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+scoped.row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="changeRole(scoped.row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scoped.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="pageConfige.size"
            :total="pageConfige.total"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
      <AddEmploy :is-show-dialog="isShowDialog" />
      <AssignRole ref="assignRole" :is-show-dialog.sync="isShowRole" />
    </div>
  </div>
</template>
<script>
// 弹窗组件
import AddEmploy from './components/add-employees.vue'
// 角色更改弹窗
import AssignRole from './components/assign-role.vue'
// import PageTools from '@/components/PageTools' PageTools
import { getEmployeeList, delEmployee } from '@/api/employees'
// 使用封装好了的枚举数据形式
import EmployeeEnum from '@/api/constant/employees'
// import user from '../../../mock/user'
// 导入插件（将数据转换为Excel表格的数据格式）
import { export_json_to_excel } from '@/vendor/Export2Excel'
// 导入过滤器中的函数
import { formatDate } from '@/filters/index'
export default {
  name: '',
  components: { AddEmploy, AssignRole },
  props: {
  },
  data() {
    return {
      employeeList: [],
      pageConfige: {
        page: 1,
        size: 5,
        total: 0
      },
      isShowDialog: false,
      isShowRole: false
    }
  },
  computed: {},
  watch: {},
  async created() {
    this.getEmployeeList()
  },
  mounted() {
  },
  methods: {
    customIndex(index) {
      // 索引应该等于前面的所有数据数量
      // 继续往下加
      // 前面所有数量=上一页页码*每页长度
      // 比如现在在第三页每页5条, 之前就有 2 * 5 共 10 数据
      // 接下来就是 11 12 13 ...
      return (this.pageConfige.page - 1) * this.pageConfige.size + index + 1
    },
    changePage(newPage) {
      this.pageConfige.page = newPage
      this.getEmployeeList()
    },
    async  getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.pageConfige)
      // console.log(res)
      // 改造数据
      this.employeeList = rows.map(user => {
        const date = new Date()
        return {
          ...user,
          timeOfEntry: date.toString(),
          enableState: 1
        }
      })
      this.pageConfige.total = total
    },
    formatEmployment(row, col, cell) {
      // 将所有可能性列举出来的数据格式，叫做枚举
      // const hireType = [
      //   { id: 1, value: '正式员工' },
      //   { id: 2, value: '临时员工' }
      // ]
      const res = EmployeeEnum.hireType.find(item => item.id === cell)
      return res ? res.value : '未知形式'
    },
    // 删除员工功能实现
    async delEmployee(id) {
      // 二次询问
      await this.$confirm('是否确定删除？')
      // 发送请求
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployeeList()
    },
    // 导出数据生成Excel表格
    async exportExcel() {
      console.log('导出')
      const { rows } = await getEmployeeList({ page: 1, size: this.pageConfige.total })
      console.log('151', rows)
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '地址'],
      //   data: [
      //     ['tom', 12, '珠吉路'],
      //     ['小陈', 19, '吉山幼儿园']
      //   ]
      // })
      // 数据转换，dict将英文的键名转换为中文的格式
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // 获取表头的数据格式，只需要键名
      // 使用Object.keys 获取对象 key 组成表头
      const header = Object.keys(dict)

      // 将用户对象转换为用户数组格式
      const data = rows.map(user => {
        const arr = []
        for (const key in dict) {
          // 按照字典的顺序，拿到每隔属性，推入到数组中
          // 在数据加入数组之前需要做一些对数据的整改
          // 1 将聘用形式的数值改为文字
          // 需要引入枚举数据
          if (dict[key] === 'formOfEmployment') {
            const val = user[dict[key]]
            const res = EmployeeEnum.hireType.find(item => item.id === val)
            arr.push(res ? res.value : '未知')
          } else if (dict[key] === 'timeOfEntry' || dict[key] === 'correctionTime') {
            // 2 将时间改成我们所熟悉的YYYY/MM/DD格式
            const val = user[dict[key]]
            arr.push(formatDate(val))
          } else {
            arr.push(user[dict[key]])
          }
        }
        return arr
      })
      // 调用生成表格的工具下载excel
      export_json_to_excel({
        header,
        data
      })
    },
    // 角色更改弹窗
    async  changeRole(employeeid) {
      await this.$refs.assignRole.getRoleIds(employeeid)
      this.isShowRole = true
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar {
  width: 180px;
  height: 80px;
  // object-fit:contain;
  object-fit: cover;
}
</style>
